using MultiAgentsServer.Scripts.Shared.enums;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.NavigationManager;
using static MultiAgentsClient.Manager.UserInfoManager;

namespace MultiAgentsClient.Presentation;
public partial record RegisterPageModel
{
    private readonly EventBus eventBus;

    public IState<string> InputUsername => State.Value(this, () => "");
    public IState<string> InputPassword => State.Value(this, () => "");
    public IState<string> InputEnsurePassword => State.Value(this, () => "");
    public IState<string> InvitationCode => State.Value(this, () => "");

    public RegisterPageModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<RegisterCompletedCommand>(cmd => Task.Run(() => RegisterResultEvent(cmd)));
    }

    public async ValueTask Register()
    {
        string? username = await InputUsername;
        string? password = await InputPassword;
        string? ensurePassword = await InputEnsurePassword;
        string? invitationCode = await InvitationCode;

        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(invitationCode))
        {
            Debug.LogWindow("注册失败，用户名、密码和邀请码不可为空。");
            return;
        }
        else if (password != ensurePassword)
        {
            Debug.LogWindow("注册失败，两次密码输入不同，请检查密码。");
            return;
        }

        eventBus.Publish(new RegisterCommand(username, password, invitationCode));
    }

    private void RegisterResultEvent(RegisterCompletedCommand cmd)
    {
        switch (cmd.Status)
        {
            case StatusCode.Status200:
                Debug.LogWindow("注册成功。");
                eventBus.Publish(new NavigationCommand(typeof(LoginPage)));
                break;
            case StatusCode.Status4000:
                Debug.LogWindow("注册失败，用户名已被使用。");
                break;
            case StatusCode.Status4001:
                Debug.LogWindow("注册失败，邀请码错误。");
                break;
            default:
                Debug.LogWindow("注册失败，未知错误，请联系管理员。");
                break;
        }
    }

    public void NavigationToLogin()
    {
        eventBus.Publish(new NavigationCommand(typeof(LoginPage)));
    }
}
